"""
数据库初始化脚本
用于创建初始数据，如初始分类、管理员用户等
"""
import os
import django

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'changdu_novel.settings')
django.setup()

from django.contrib.auth import get_user_model
from novel.models import Category, Novel, Chapter
from django.db import transaction

User = get_user_model()


@transaction.atomic
def init_db():
    """初始化数据库数据"""
    print("开始初始化数据...")

    # 创建管理员用户
    if not User.objects.filter(username='admin').exists():
        admin_user = User.objects.create_superuser(
            username='admin',
            email='admin@example.com',
            password='admin123',
            role='admin'
        )
        print("创建管理员用户: admin")
    else:
        admin_user = User.objects.get(username='admin')
        print("管理员用户已存在")

    # 创建测试作者
    if not User.objects.filter(username='author').exists():
        author_user = User.objects.create_user(
            username='author',
            email='author@example.com',
            password='author123',
            role='author'
        )
        print("创建测试作者: author")
    else:
        author_user = User.objects.get(username='author')
        print("测试作者已存在")

    # 创建测试读者
    if not User.objects.filter(username='reader').exists():
        reader_user = User.objects.create_user(
            username='reader',
            email='reader@example.com',
            password='reader123',
            role='reader'
        )
        print("创建测试读者: reader")
    else:
        reader_user = User.objects.get(username='reader')
        print("测试读者已存在")

    # 创建初始分类
    categories = [
        "玄幻", "奇幻", "武侠", "仙侠", "都市", "现实", "军事", "历史", "游戏", "体育", "科幻", "灵异"
    ]

    for category_name in categories:
        if not Category.objects.filter(name=category_name).exists():
            Category.objects.create(name=category_name)
            print(f"创建分类: {category_name}")
        else:
            print(f"分类已存在: {category_name}")

    # 创建示例小说
    if not Novel.objects.filter(title='示例小说').exists():
        category = Category.objects.first()
        novel = Novel.objects.create(
            title='示例小说',
            author=author_user,
            category=category,
            description='这是一本用于演示的示例小说。',
            status='approved'
        )

        # 创建示例章节
        Chapter.objects.create(
            novel=novel,
            title='第一章 开始',
            content='这是第一章的内容。\n\n故事从这里开始...',
            order=1
        )

        Chapter.objects.create(
            novel=novel,
            title='第二章 发展',
            content='这是第二章的内容。\n\n故事继续发展...',
            order=2
        )

        print("创建示例小说和章节")
    else:
        print("示例小说已存在")

    print("数据初始化完成！")


if __name__ == "__main__":
    init_db()